package com.pipe.protocol.events.write;

import com.pipe.util.MyBytebufUtil;
import com.pipe.util.MysqlProtocolUtil;
import io.netty.buffer.ByteBuf;

import java.util.Arrays;

/**
 * @author Kiven
 */
public class WriteRowEventV2Body {

    /**
     * If the table id is 0x00ffffff it is a dummy event that
     * should have the end of statement flag set that declares
     * that all table maps can be freed. Otherwise it refers to
     * a table defined by TABLE_MAP_EVENT.
     */
    private long columnNum;
    private byte[] cloumnsPresentBitmapOne;
    /**if UPDATE_ROWS_EVENTv1 or v2*/
    private byte[] cloumnsPresentBitmapTwo;

    public WriteRowEventV2Body(long columnNum, byte[] cloumnsPresentBitmapOne) {
        this.columnNum = columnNum;
        this.cloumnsPresentBitmapOne = cloumnsPresentBitmapOne;
    }

    public WriteRowEventV2Body(long columnNum, byte[] cloumnsPresentBitmapOne, byte[] cloumnsPresentBitmapTwo) {
        this.columnNum = columnNum;
        this.cloumnsPresentBitmapOne = cloumnsPresentBitmapOne;
        this.cloumnsPresentBitmapTwo = cloumnsPresentBitmapTwo;
    }

    public long getColumnNum() {
        return columnNum;
    }

    public static WriteRowEventV2Body build(ByteBuf byteBuf, boolean isUpdate){
        long cn = MysqlProtocolUtil.readLenencIntFromBytebuf(byteBuf);

        byte[] cpb1 = MyBytebufUtil.readByteFromBytebuf(byteBuf, (int)((cn + 7)/8) );

        if (isUpdate){
            byte[] cpb2 = MyBytebufUtil.readByteFromBytebuf(byteBuf, (int)((cn + 7)/8) );
            return new WriteRowEventV2Body(cn, cpb1, cpb2);
        }
        return new WriteRowEventV2Body(cn, cpb1);
    }

    @Override
    public String toString() {
        return "WriteRowEventV2Body{" +
                "columnNum=" + columnNum +
                ", cloumnsPresentBitmapOne=" + Arrays.toString(cloumnsPresentBitmapOne) +
                ", cloumnsPresentBitmapTwo=" + Arrays.toString(cloumnsPresentBitmapTwo) +
                '}';
    }
}